package com.zzwtec.validation.core;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;



/**
 * 核心配置文件 
 * @author 草原狼
 * 2017年8月22日
 */

public class Configuration {
	Properties ps = null;
	//验证器
	Map<String, Object> validatorMap = new HashMap<String, Object>();
	String engine = "com.zzwtec.validation.core.DefaultRuntimeEngine";
	
	public String getEngine() {
		return engine;
	}

	public void setEngine(String engine) {
		this.engine = engine;
	}

	public Configuration() throws IOException {
		ps = new Properties();
		ps.load(Configuration.class.getResourceAsStream("/com/zzwtec/validation/core/validator-default.properties"));
		parseProperties(ps);
		InputStream ins = Configuration.class.getResourceAsStream("/validator.properties");
		if (ins != null){
			ps.clear();
			ps.load(ins);
			parseProperties(ps);
		}
	}

	protected void parseProperties(Properties ps) {
		Set<Map.Entry<Object, Object>> set = ps.entrySet();
		for (Map.Entry<Object, Object> entry : set) {
			String key = (String) entry.getKey();
			String value = (String) entry.getValue();
			setValue(key, value);
		}
	}

	protected void setValue(String key, String value) {
		if (key.startsWith("valid.") || key.startsWith("VALID.")) {		
			addValidator(key, value);
		}
	}

	private String getExtName(String key){
		int index = key.indexOf(".");
		String name = key.substring(index + 1);
		return name;
	}
	
	/**
	 * 添加验证器
	 * @param key
	 * @param value
	 */
	private void addValidator(String key, String value) {
		String name = this.getExtName(key);
		try {
			this.validatorMap.put(name, Class.forName(value).newInstance());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
